import { login, getConfig, logout } from '../../api/user'

const state = {
  status: false,
  config: '',
}

const mutations = {
  SET_STATUS: (state, status) => {
    state.status = status
  },
  SET_CONFIG: (state, config) => {
    state.config = config
  },
}

const actions = {
  // user login
  login ({commit}, userInfo) {
    const {username, password} = userInfo
    return new Promise((resolve, reject) => {
      login({username: username.trim(), password: password})
        .then((response) => {
          const {data} = response
          commit('SET_STATUS', data.status)
          resolve()
        })
        .catch((error) => {
          reject(error)
        })
    })
  },

  // get user config
  getConfig ({commit, state}) {
    return new Promise((resolve, reject) => {
      if (state.config) {
        resolve(state.config)
      } else {
        getConfig()
          .then((response) => {
            const {data} = response
            if (!data.status) {
              reject('验证登录信息失败，请重新登录！')
            }
            commit('SET_CONFIG', data)
            resolve(data)
          })
          .catch((error) => {
            reject(error)
          })
      }
    })
  },

  // user logout
  logout ({commit}) {
    return new Promise((resolve, reject) => {
      logout()
        .then((res) => {
          commit('SET_STATUS', false)
          commit('SET_CONFIG', '')
          resolve(res)
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
